package com.yesin.item.service;

import com.yesin.geteway.exception.ExceptionEnum;
import com.yesin.geteway.exception.YsException;
import com.yesin.item.mapper.SpecGroupMapper;
import com.yesin.item.mapper.SpecParamMapper;
import com.yesin.item.pojo.SpecGroup;
import com.yesin.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class SpecificationService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper paramMapper;

    /**
     * 根据父节点查询商品分类
     * @param cid
     * @return
     */
    public List<SpecGroup> queryGroupsBycid(Long cid) {
        // 检查 cid 不能为空
        if (cid == null){
            return null;
        }
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        // 开始查询
        List<SpecGroup> groups = this.specGroupMapper.select(specGroup);
        // 查询结果为空，失败
        if (CollectionUtils.isEmpty(groups)){
            throw new YsException(ExceptionEnum.GROUPSPEC_NOT_FOUND);
        }
        groups.forEach(group -> {
            SpecParam specParam = new SpecParam();
            specParam.setGroupId(group.getId());
            group.setParams(this.paramMapper.select(specParam));
        });

        return groups;

    }

    /**
     * 根据条件查询规格参数
     *
     * @param gid
     * @param cid
     * @param generic
     * @param searching
     * @return
     */
    public List<SpecParam> queryParams(Long gid, Long cid, Boolean generic, Boolean searching) {
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setGeneric(generic);
        specParam.setSearching(searching);
        return paramMapper.select(specParam);
    }
}
